﻿/****************************************************************************************************
	Copyright (C) 2010 RapidWebDev Organization (http://rapidwebdev.org)
	Author: Eunge, Legal Name: Jian Liu, Email: eunge.liu@RapidWebDev.org

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ****************************************************************************************************/

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.SessionState;
using BaoJianSoft.Common;
using BaoJianSoft.Common.CodeDom;
using BaoJianSoft.Common.Web;
using BaoJianSoft.Common.Validation;
using BaoJianSoft.RapidWeb.Controls;
using BaoJianSoft.RapidWeb.DynamicPages;
using BaoJianSoft.RapidWeb.DynamicPages.Configurations;
using BaoJianSoft.RapidWeb.Properties;
using Spring.Objects;

namespace BaoJianSoft.RapidWeb.Services
{
	/// <summary>
	/// The service is to create an html document file for clients to print based on query criteria submitted.
	/// </summary>
	public class DynamicPageDataToHtmlHandler : IHttpHandler, IRequiresSessionState
	{
		/// <summary>
		/// The server encountered an unknown error when accessing the URI {0}.
		/// </summary>
		private const string UNKNOWN_ERROR_LOGGING_MSG = "The server encountered an unknown error when accessing the URI {0}.";

		private static readonly IDynamicPagePrinter dynamicPagePrinter = SpringContext.Current.GetObject<IDynamicPagePrinter>("DynamicPageHtmlPrinter");
		private static readonly IPermissionBridge permissionBridge = SpringContext.Current.GetObject<IPermissionBridge>();

		bool IHttpHandler.IsReusable { get { return true; } }

		void IHttpHandler.ProcessRequest(HttpContext context)
		{
			try
			{
				this.ProcessRequest(context);

				context.Response.StatusCode = (int)HttpStatusCode.OK;
			}
			catch (ThreadAbortException)
			{
			}
			catch (UnauthorizedAccessException)
			{
				WebUtility.RedirectToPage(WebUtility.NotAuthorizedUrl);
			}
			catch (ValidationException)
			{
				WebUtility.RedirectToPage(WebUtility.PageNotFoundUrl);
			}
			catch (Exception exp)
			{
				Logger.Instance(this).Error(exp);
				WebUtility.RedirectToPage(WebUtility.InternalServerError);
			}
		}

		private void ProcessRequest(HttpContext context)
		{
			if (Kit.IsEmpty(QueryStringUtility.ObjectId))
				throw new BadRequestException("The query string parameter ObjectId is not specified.");

			string objectId = QueryStringUtility.ObjectId;
			IDynamicPage dynamicPageService = null;
			try
			{
				dynamicPageService = DynamicPageContext.Current.GetDynamicPage(objectId, false);
			}
			catch (ConfigurationErrorsException)
			{
				throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, "The query string parameter ObjectId \"{0}\" is invalid. Please be caution the parameter is case sensitive.", objectId));
			}

			if (!permissionBridge.HasPermission(dynamicPageService.Configuration.PermissionValue))
				throw new UnauthorizedAccessException();

			DynamicPagePrintResult printResult = dynamicPagePrinter.Print(dynamicPageService, HttpContext.Current.Request.QueryString);
			HttpContext.Current.Response.Redirect(printResult.Result, true);
		}
	}
}
